package com.rongshu.view.penpal.activity;

import android.animation.Animator;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rongshu.R;
import com.rongshu.eventbus.PostComment;
import com.rongshu.utils.AnimationUtil;
import com.rongshu.utils.Constant;
import com.rongshu.utils.ControlScrollLayoutManager;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.GlideUtils;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.activity.PreviewImgActivity;
import com.rongshu.view.home.adapter.CommentAdapter;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.fragment.dialog.InputNoteDialog;
import com.rongshu.view.home.fragment.dialog.SharePenpalAndThirdDialog;
import com.rongshu.view.home.listener.OnItemFunctionClickListener;
import com.rongshu.view.home.widget.SelectableTextView;
import com.rongshu.view.home.widget.favor.FavorLayout;
import com.rongshu.view.penpal.adapter.PostInsertImgAdapter;
import com.rongshu.view.penpal.bean.PostDetailsResponse;
import com.rongshu.view.penpal.present.PostDetailsPresenter;
import com.rongshu.view.penpal.view.PostDetailsView;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.rongshu.widget.BanyanDialog;
import com.rongshu.widget.YNestedScrollView;
import com.rongshu.widget.xrichtext.RichTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.socialize.UMShareAPI;
import com.utils.FastClickUtils;
import com.utils.LogUtil;
import com.utils.SPUtils;
import com.utils.StringUtils;
import com.utils.constants.SPKey;
import com.widget.CircleImageView;
import com.widget.dialog.BottomListDialog;
import com.widget.loading.AnimatorListener;
import com.widget.titlebar.ImmersionBar;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

import static com.rongshu.utils.UserInfoUtils.getUserId;

/**
 * created by zhengweis on 2018/11/1.
 * description：帖子详情页面
 */
public class PostDetailsActivity extends BaseActivity<PostDetailsPresenter> implements PostDetailsView, OnItemFunctionClickListener {
    @BindView(R.id.layout_parent)
    RelativeLayout layout_parent;
    @BindView(R.id.penpal_name)
    TextView penpalName;
    @BindView(R.id.layout_top_menu)
    RelativeLayout layoutTopMenu;
    @BindView(R.id.user_logo)
    CircleImageView userLogo;
    @BindView(R.id.author_level)
    TextView authorLevel;
    @BindView(R.id.author_name)
    TextView authorName;
    @BindView(R.id.article_time)
    TextView articleTime;
    @BindView(R.id.author_content)
    RelativeLayout authorContent;
    @BindView(R.id.article_title)
    SelectableTextView articleTitle;
    @BindView(R.id.article_content)
    RichTextView articleContent;
    @BindView(R.id.comment_list)
    RecyclerView commentList;
    @BindView(R.id.comment_num)
    TextView commentNum;
    @BindView(R.id.praise_num)
    TextView praiseNum;
    @BindView(R.id.bottom_option)
    RelativeLayout bottomOption;
    @BindView(R.id.layout_add_attention)
    RelativeLayout keepAuthorLayout;
    @BindView(R.id.refresh_view)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;
    @BindView(R.id.in_penpal)
    TextView joinBtn;
    @BindView(R.id.praise_img)
    ImageView praiseImg;
    @BindView(R.id.right_option)
    LinearLayout rightOption;
    @BindView(R.id.comment_layout)
    LinearLayout commentLayout;
    @BindView(R.id.scroll_view)
    YNestedScrollView scrollView;
    @BindView(R.id.post_img)
    RecyclerView postImg;
    private List<CommentDetails.ResponseBean> comments;//评论列表
    private int postId;
    private PostDetailsResponse.ResponseBean bean;
    private boolean isConcern = false;
    private CommentAdapter adapter = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    private int replyPageIndex = 1;
    private int replyPageSize = 100;
    //评论ID,回复ID
    private int comment_id = 0, reply_id = 0;
    //local_position 局部刷新position
    private int local_position;
    private int praisePosition;//标记点赞的item
    private boolean showJoinIcon = false;
    //帖子的插图
    private ArrayList<String> insertImageUrls;
    private PostInsertImgAdapter insertImgAdapter;
    //是否删除为回复
    private boolean isDeteleReply = false;
    //复制，回复，删除dialog
    private List<String> functions = null;
    //删除评论回复的position
    private int replyPosition = 0;
    //是否手动点赞
    private boolean isManualLike = false;
    //点赞爱心
    private FavorLayout favorLayout = null;
    //点赞提示语
    private List<String> likeTips = null;
    //dialog
    private InputNoteDialog inputNoteDialog = null;
    //内容
    private String mContent = "";
    //提示
    private String mReplyContent = null;
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap = null;
    //offsetDistance
    private int offsetDistance = 0;
    //touch 过程不进行记录
    private boolean isTouch = false;
    //是否滑动到了评论区域
    private boolean isScrollToComment = false;
    //scrollY
    private int mScrollY = 0;
    //bodyLocation
    private int lastBodyLocation = 0;
    //commentLocation
    private int lastCommentLocation = 0;
    //滑动标识
    private final int scrollMessage = 0x0e;
    //hander
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case scrollMessage:
                    handler.removeMessages(scrollMessage);
                    if (mScrollY == scrollView.getScrollY()) {
                        isTouch = false;
                        return;
                    }
                    handler.sendEmptyMessageDelayed(scrollMessage, 1000);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.with(this).keyboardEnable(false,
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
                .init();
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .init();  //必须调用方可沉浸式
        } else {
            bar.flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f)
                    .init();  //必须调用方可沉浸式
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_post_details;
    }

    @Override
    protected void initView() {
        smartRefreshLayout.setEnableAutoLoadmore(true);
        //manager
        ControlScrollLayoutManager manager = new ControlScrollLayoutManager(this);
        manager.setScrollEnabled(false);
        comments = new ArrayList<>();
        //list
        likeTips = Arrays.asList(new String[]{
                getString(R.string.its_nice_to_be_liked),
                getString(R.string.received_your_like_thank_you),
                getString(R.string.once_thumb_up_very_close),
                getString(R.string.warm_praise_reliable_shoulder),
                getString(R.string.thanks_for_your_encouragement)});
        //adapter
        adapter = new CommentAdapter(this);
        adapter.setResponseBeanList(comments);
        adapter.setHasStableIds(true);
        adapter.setOnItemFunctionClickListener(this);
        //recyclerview
        commentList.setLayoutManager(manager);
        commentList.setAdapter(adapter);
        //帖子的插图
        ControlScrollLayoutManager layoutManager = new ControlScrollLayoutManager(this);
        layoutManager.setScrollEnabled(false);
        postImg.setLayoutManager(layoutManager);
        insertImageUrls = new ArrayList<>();
        insertImgAdapter = new PostInsertImgAdapter(this, insertImageUrls);
        postImg.setAdapter(insertImgAdapter);
        //@list
        authorDetailBeanMap = new LinkedHashMap<>();
        //爱心
        favorLayout = new FavorLayout(this);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelOffset(R.dimen.dd_dimen_700px));
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lp.bottomMargin = getResources().getDimensionPixelOffset(R.dimen.dd_dimen_32px);
        lp.leftMargin = getResources().getDimensionPixelOffset(R.dimen.dd_dimen_210px);
        favorLayout.setLayoutParams(lp);
        layout_parent.addView(favorLayout);
        offsetDistance = (int) getResources().getDimension(R.dimen.dd_dimen_160px);
        //nested_scroll_view listener
        scrollView.setOnScrollChangeListener(new YNestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(YNestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                mScrollY = scrollY;
                int commentLocation = commentLayout.getTop() - v.getMeasuredHeight();
                if (scrollY >= commentLocation) {
                    isScrollToComment = true;
                }
                if (!isTouch) {
                    if (scrollY >= commentLayout.getTop() - scrollView.getMeasuredHeight() + 2 * offsetDistance) {
                        lastCommentLocation = scrollY;
                    } else {
                        lastBodyLocation = scrollY;
                    }
                } else {
                    handler.sendEmptyMessageDelayed(scrollMessage, 1000);
                }
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            postId = intent.getIntExtra(Constant.POST_ID, 0);
            showJoinIcon = intent.getBooleanExtra("showJoinIcon", false);
        }
        setPresenter(new PostDetailsPresenter(this), this);
        presenter.getPostDetails(postId);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageIndex = 1;
                refreshlayout.resetNoMoreData();
                presenter.getCommentDetail(bean.getId(), 0, pageIndex, pageSize);
            }
        });

        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                presenter.getCommentDetail(bean.getId(), 0, pageIndex, pageSize);
            }
        });
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    //接口返回的帖子详情
    @Override
    public void onPostMsg(PostDetailsResponse response) {
        if (response != null && response.getResponse() != null) {
            if (showJoinIcon) {
                joinBtn.setVisibility(View.GONE);
            }
            bean = response.getResponse();
            penpalName.setText(bean.getPenclubname());
            GlideUtils.loadImageView(this, userLogo, bean.getAvatar(), R.drawable.user_head_icon, R.drawable.user_head_icon);
            authorName.setText(bean.getBi_name());
            if (bean.getRank() == 1) {
                authorLevel.setText("会长");
            } else {
                authorLevel.setVisibility(View.GONE);
            }
            isConcern = bean.getIsConcern() != 0;
            keepAuthorLayout.setVisibility(bean.getIsConcern() == 1 ? View.GONE : View.VISIBLE);
            articleTitle.setVisibility(TextUtils.isEmpty(bean.getTitle()) ? View.GONE : View.VISIBLE);
            articleTitle.setText(bean.getTitle());
            articleTime.setText(DateUtils.ConvertDate(bean.getCreate_datetime()));
            commentNum.setText(String.valueOf(bean.getCommentCount()));
            praiseNum.setText(String.valueOf(bean.getLikeCount()));
            praiseImg.setBackgroundResource(bean.getIslike() == 0 ? R.drawable.love_gray_smasll_icon : R.drawable.love_red_small_icon);
            pageIndex = 1;
            presenter.getCommentDetail(bean.getId(), 0, pageIndex, pageSize);
            //帖子内容
            String spanned = Html.fromHtml(bean.getContents()).toString();
            LogUtil.d(spanned);
            //类型
            int fontType = SPUtils.getPreferences(SPKey.FONTPATTERN, 1);
            articleContent.setRtTextSize((int) getResources().getDimension(Constant.contentSizes[fontType]));
            articleContent.clearAllLayout();
            if (TextUtils.isEmpty(StringUtils.getImgSrc(bean.getContents()))) {
                articleContent.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String content = bean.getContents().replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                            articleContent.addTextViewAtIndex(URLDecoder.decode(content.trim(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                });
                String postPictures = bean.getPostPictures();
                String[] split = postPictures.split("\\|");
                for (String picture : split) {
                    if (!TextUtils.isEmpty(picture)) {
                        insertImageUrls.add(picture);
                        LogUtil.d("========" + picture);
                    }
                }
                insertImgAdapter.notifyDataSetChanged();
            } else {
                articleContent.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String content = bean.getContents().replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                            presenter.dealWithContent(URLDecoder.decode(content, "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                });
                articleContent.setOnRtImageClickListener(new RichTextView.OnRtImageClickListener() {
                    @Override
                    public void onRtImageClick(String imagePath) {
                        ArrayList<String> listA = new ArrayList<>();
                        listA.addAll(articleContent.getImagePaths());
                        Intent intent = new Intent(PostDetailsActivity.this, PreviewImgActivity.class);
                        intent.putExtra(Constant.INTENT_MESSAGE, imagePath);
                        intent.putStringArrayListExtra(Constant.INTENT_DATA, listA);
                        startActivity(intent);
                    }
                });
            }
        }
    }

    //接口返回的该帖子评论详情
    @Override
    public void onCommentMsg(List<CommentDetails.ResponseBean> responseBeanList) {
        showLoading(false);
        if (pageIndex == 1) {
            comments.clear();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        comments.addAll(responseBeanList);
        adapter.notifyDataSetChanged();
        if (responseBeanList.size() < pageSize) {
            smartRefreshLayout.setLoadmoreFinished(true);
        }
        layout_empty.setVisibility(comments.size() == 0 ? View.VISIBLE : View.GONE);
    }

    //发送评论成功
    @Override
    public void commentSuccess(ResponseBody body) {
        toast("留言成功");
        try {
            String json = body.string().toString();
            JSONObject object = new JSONObject(json);
            int errCode = object.getInt("ErrCode");
            String errMsg = object.getString("ErrMsg");
            String respose = object.getString("Response");
            if (errCode == 0) {
                if (comment_id == 0) {//文章评论
                    CommentDetails details = new Gson().fromJson(json, CommentDetails.class);
                    List<CommentDetails.ResponseBean> beanList = details.getResponse();
                    if (beanList != null && !beanList.isEmpty()) {
                        //本地追加评论
                        CommentDetails.ResponseBean bean = beanList.get(0);
                        //原先评论
                        List<CommentDetails.ResponseBean> beans = new ArrayList<>();
                        beans.addAll(comments);
                        //显示评论区，隐藏
                        layout_empty.setVisibility(View.GONE);
                        //清空集合，填充新数据
                        comments.clear();
                        comments.add(bean);
                        if (!beans.isEmpty()) {
                            comments.addAll(beans);
                        }
                        adapter.notifyDataSetChanged();
                    }
                    //如果评论增加，则评论数需要增加1
                    if (bean == null) {
                        return;
                    }
                    int count = bean.getCommentCount();
                    count = count + 1;
                    bean.setCommentCount(count);
                    commentNum.setText(String.valueOf(bean.getCommentCount()));
                } else {//评论回复，以及回复的回复
                    List<CommentReplysBean> replysBeans = new Gson().fromJson(respose, new TypeToken<List<CommentReplysBean>>() {
                    }.getType());
                    if (replysBeans != null && !replysBeans.isEmpty()) {
                        //原先的评论回复
                        if (comments != null && !comments.isEmpty()) {
                            List<CommentReplysBean> list = new ArrayList<>();
                            CommentDetails.ResponseBean bean = comments.get(local_position);
                            List<CommentReplysBean> replys = bean.getComment_replys();
                            //重新填充一个集合
                            list.addAll(replys);
                            replys.clear();
                            replys.add(replysBeans.get(0));
                            if (!list.isEmpty()) {
                                //添加以前的数据
                                replys.addAll(list);
                            }
                            //此时，comment_replyCount数量需要增加1
                            int count = bean.getComment_replyCount();
                            count = count + 1;
                            bean.setComment_replyCount(count);
                            adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                        }
                    }
                }
                if (comment_id == 0) {
                    if (mScrollY < commentLayout.getTop() - scrollView.getMeasuredHeight() + offsetDistance) {
                        scrollView.smoothScrollTo(0, commentLayout.getTop());
                    }
                }
                clean();
            } else {
                toast(errMsg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void clean() {
        inputNoteDialog.dismissDialog();
        local_position = 0;
        isDeteleReply = false;
        replyPosition = 0;
        comment_id = 0;
        reply_id = 0;
        authorDetailBeanMap.clear();
    }

    /**
     * 单个评论下的所有回复
     *
     * @param commentReplysBeans
     */
    @Override
    public void onOnecommentDetail(List<CommentReplysBean> commentReplysBeans) {
        if (adapter == null) {
            return;
        }
        adapter.getResponseBeanList().get(local_position).setComment_replys(commentReplysBeans);
        adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
    }


    //评论点赞/取消点赞成功
    @Override
    public void onCommentlike() {
        List<CommentDetails.ResponseBean> responseBeanList = adapter.getResponseBeanList();
        if (responseBeanList != null) {
            int likeCount = responseBeanList.get(praisePosition).getLikeCount();
            responseBeanList.get(praisePosition).setLikeCount(likeCount + 1);
            responseBeanList.get(praisePosition).setIslike(1);
            adapter.notifyItemRangeChanged(praisePosition, 1, adapter.GIVELIKE);
        }
    }

    //帖子点赞返回
    @Override
    public void onPostList() {
        if (bean != null) {
            bean.setIslike(bean.getIslike() == 0 ? 1 : 0);
            praiseImg.setBackgroundResource(bean.getIslike() == 0 ? R.drawable.love_gray_smasll_icon : R.drawable.love_red_small_icon);
            if (bean.getIslike() == 1 && isManualLike) {
                isManualLike = false;
                favorLayout.addFavor();
                toast(likeTips.get(new Random().nextInt(likeTips.size())));
            }
            int praise = Integer.valueOf(praiseNum.getText().toString().trim());
            if (bean.getIslike() == 0) {
                praise--;
            } else {
                praise++;
            }
            praiseNum.setText(praise + "");
            bean.setLikeCount(praise);
        }
    }

    @Override
    public void onCallBackDealWithContent(String content) {
        if (articleContent != null) {
            if (content.contains("<img") && content.contains("src=")) {
                //imagePath可能是本地路径，也可能是网络地址
                String imagePath = StringUtils.getImgSrc(content);
                articleContent.addImageViewAtIndex(imagePath, false);
            } else {
                if (!TextUtils.equals("</p><p>", content.trim()) || !TextUtils.equals("</br><br>", content.trim())) {
                    articleContent.addTextViewAtIndex(content.trim());
                }
            }
        }
    }

    @Override
    public void onCommentDelete(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            if (adapter == null) {
                return;
            }
            List<CommentDetails.ResponseBean> responseBeans = adapter.getResponseBeanList();
            if (isDeteleReply) {//回复评论
                CommentDetails.ResponseBean response = responseBeans.get(local_position);
                List<CommentReplysBean> replysBeans = response.getComment_replys();
                replysBeans.remove(replyPosition);
                int comment_replyCount = response.getComment_replyCount();
                if (comment_replyCount > 0) {
                    comment_replyCount = comment_replyCount - 1;
                    response.setComment_replyCount(comment_replyCount);
                }
                //如果此时集合中数据和comment_replyCount数据不一致，说明二者数据不一致，需要重新请求
                int replyCount = replysBeans.size();
                if (replyCount < comment_replyCount) {
                    adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                    presenter.getOnecommentDetail(comment_id, replyPageIndex, replyPageSize);//(此处问题在于，如果获取不到数据，当前一条没有更新view)
                } else {
                    adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                }
            } else {//回复文章
                responseBeans.remove(local_position);
                adapter.notifyItemRemoved(local_position);
                adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                //如果评论删除，则评论数需要减去1
                if (bean == null) {
                    return;
                }
                int count = bean.getCommentCount();
                count = count <= 0 ? 0 : count - 1;
                bean.setCommentCount(count);
                commentNum.setText(String.valueOf(bean.getCommentCount()));
            }
            int itemCount = adapter.getItemCount();
            layout_empty.setVisibility(itemCount == 0 ? View.VISIBLE : View.GONE);
        } else {
            toast(iNetBean.getErrMsg());
        }
        showKeyboard(false);
        clean();
    }

    public void intentPersonHomepage(PostDetailsResponse.ResponseBean responseBean) {
        if (UserInfoUtils.getUserId() == responseBean.getId()) {
            Intent intent = new Intent(this, PersonDetailsActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, responseBean.getPoster_userid());
            startActivityForResult(intent, INTENT_USER_HOME_QUESTCODE);
        }
    }

    @OnClick({R.id.head_left, R.id.in_penpal, R.id.layout_add_attention, R.id.user_logo, R.id.share_layout,
            R.id.praise_layout, R.id.comment_option, R.id.comment_content})
    public void onViewClicked(View view) {
        if (FastClickUtils.isFastClick()) {
            return;
        }
        final Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.head_left:
                showKeyboard(false);
                onBackPressed();
                break;
            case R.id.share_layout:
                if (UserInfoUtils.getUserInfo() != null) {
                    SharePenpalAndThirdDialog.Builder builder = new SharePenpalAndThirdDialog.Builder(this);
                    builder.setContribute_id(bean.getId()).setType_id(2).create().show();
                } else {
                    LoginUtils.toLogin(this);
                }
                break;
            case R.id.user_logo:
                if (bean != null) {
                    if (UserInfoUtils.getUserInfo() == null) {
                        LoginUtils.toLogin(this);
                    } else {
                        intentPersonHomepage(bean);
                    }
                }
                break;
            case R.id.in_penpal:
                if (getUserId() == 0) {
                    LoginUtils.toLogin(PostDetailsActivity.this);
                    return;
                }
                intent.setClass(this, PenpalDetailActivity.class);
                intent.putExtra(Constant.PENPAL_ID, bean.getPenpalwill_id());
                startActivity(intent);
                break;
            case R.id.layout_add_attention:
                if (UserInfoUtils.getUserInfo() != null) {
                    isConcern = !isConcern;
                    presenter.ConcernWith(bean.getPoster_userid());
                    AnimationUtil.AlphaScaleAnimator(keepAuthorLayout, new AnimatorListener() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            keepAuthorLayout.setVisibility(View.GONE);
                            keepAuthorLayout.animate().alpha(1).scaleX(1).scaleY(1);
                        }
                    });
                } else {
                    LoginUtils.toLogin(this);
                }
                break;
            case R.id.praise_layout:
                if (UserInfoUtils.getUserInfo() != null) {
                    //用户数据不为空，用户未点过赞
                    if (bean != null && bean.getIslike() == 0) {
                        isManualLike = true;
                        presenter.getlike(bean.getId());
                    } else {
                        presenter.getOfflike(bean.getId());
                    }
                } else {
                    LoginUtils.toLogin(this);
                }
                break;
            case R.id.comment_option:
                isTouch = true;
                if (lastBodyLocation == 0 && lastCommentLocation == 0) {
                    if (mScrollY + scrollView.getMeasuredHeight() >= commentLayout.getTop()) {
                        scrollView.smoothScrollTo(0, 0);
                    } else {
                        scrollView.smoothScrollTo(0, commentLayout.getTop());
                    }
                } else {
                    if (mScrollY >= commentLayout.getTop() - scrollView.getMeasuredHeight() + 2 * offsetDistance) {
                        if (lastBodyLocation == 0) {
                            scrollView.smoothScrollTo(0, 0);
                            return;
                        }
                        scrollView.smoothScrollTo(0, lastBodyLocation);
                    } else {
                        if (lastCommentLocation == 0) {
                            scrollView.smoothScrollTo(0, commentLayout.getTop());
                            return;
                        }
                        scrollView.smoothScrollTo(0, lastCommentLocation);
                    }
                }
                int comment = bean.getCommentCount();
                if (comment == 0 && !isScrollToComment && UserInfoUtils.getUserId() != 0) {
                    getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                } else {
                    isScrollToComment = false;
                }
                break;
            case R.id.comment_content:
                if (UserInfoUtils.getUserId() == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                break;
        }
    }

    /**
     * 显示输入框弹窗
     */
    private InputNoteDialog getInputDialog() {
        inputNoteDialog = InputNoteDialog.getInstance(mContent, mReplyContent, authorDetailBeanMap);
        inputNoteDialog
                .setOnDialogInputListener(new InputNoteDialog.OnDialogInputListener() {
                    @Override
                    public void sendCommentSuccess(LinkedHashMap<String, AuthorDetailBean> map, String content) {
                        presenter.postComment(authorDetailBeanMap, bean.getPenpalwill_id(), bean.getId(),
                                comment_id, reply_id, Uri.encode(content, "utf-8"));
                    }

                    @Override
                    public void dimiss(LinkedHashMap<String, AuthorDetailBean> map, String content, String replyContent) {
                        inputNoteDialog.dismissDialog();
                        inputNoteDialog = null;
                        authorDetailBeanMap = map;
                        mContent = content;
                        mReplyContent = replyContent;
                    }
                });
        return inputNoteDialog;
    }


    @Override
    public void onBackPressed() {
        if (bean != null) {
            Intent intent = new Intent();
            intent.putExtra(Constant.LIKE_COUNT, bean.getLikeCount());
            intent.putExtra(Constant.COMMENT_COUNT, bean.getCommentCount());
            setResult(RESULT_OK, intent);
        }
        super.onBackPressed();
    }

    /**
     * 复制，回复，删除评论dialog
     */
    private void showCopyReplyDeleteDialog(final String contents, final String bi_name, final int c_id, final int r_id, int from_uid) {
        if (adapter == null) {
            return;
        }
        if (bean == null) {
            return;
        }
        //复制，回复，删除
        functions = new ArrayList<>();
        functions.add("复制");
        functions.add("回复");
        //当前登录id
        int user_id = UserInfoUtils.getUserId();
        //当前文章的用户id
        int article_user_id = bean.getPoster_userid();
        //如果(1.登录id==文章的用户id,则是自己的文章，可以删除)(2.如果来自from_uid==登录id，可以删除)
        if (user_id == article_user_id || user_id == from_uid) {
            functions.add("删除");
        }
        BottomListDialog.Builder builder = new BottomListDialog.Builder(this);
        builder.setFunctions(functions)
                .setCancle(getString(R.string.cancle))
                .setCancle_color(R.color.color_2c2c2c)
                .setOption_color(R.color.color_2c2c2c)
                .setOnItemClickListener(new BottomListDialog.Builder.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Dialog dialog) {
                        dialog.dismiss();
                        String funtion = functions.get(position);
                        if (funtion.equals("复制")) {
                            ClipboardManager mCM = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                            mCM.setPrimaryClip(ClipData.newPlainText(null, contents));
                            toast("复制成功");
                        } else if (funtion.equals("回复")) {
                            comment_id = c_id;
                            reply_id = r_id;
                            mReplyContent = "回复：" + bi_name;
                            getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                        } else if (funtion.equals("删除")) {
                            comment_id = c_id;
                            reply_id = r_id;
                            deleteCommentDeleteDialog();
                        }
                    }
                }).create().show();
    }

    /**
     * 删除该条评论提示
     */
    private void deleteCommentDeleteDialog() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("确认要删除该条评论吗？")
                .setLeft("取消")
                .setRight("确定");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                if (bean == null) {
                    return;
                }
                presenter.postDeleteComment(bean.getId(), comment_id, reply_id);
            }
        });
        dialog.show();
    }

    @Override
    public void onItemClickListener(int position, String contents, String bi_name, int comment_id, int from_uid) {//点击回复
        this.local_position = position;
        this.isDeteleReply = false;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, 0, from_uid);
    }

    @Override
    public void onItemChildClickListener(int position, int replyPosition, String contents, String bi_name, int comment_id, int reply_id, int reply_user_id) {
        this.local_position = position;
        this.replyPosition = replyPosition;
        this.isDeteleReply = true;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, reply_id, reply_user_id);
    }

    @Override
    public void onItemExpandClickListener(boolean isExpanded, int pageSize, int comment_id, int local_position) {
        if (isExpanded) {
            this.isDeteleReply = false;
            this.local_position = local_position;
            presenter.getOnecommentDetail(comment_id, replyPageIndex, replyPageSize);
        } else {
            if (adapter == null) {
                return;
            }
            adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
        }
    }

    @Override
    public void onItemHeaderClickListener(int userid, boolean is_allow_browse_homepage) {
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        Intent intent = null;
        if (user_id == userid) {
            intent = new Intent(this, PersonDetailsActivity.class);
        } else {
            intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userid);
        }
        startActivity(intent);
    }

    @Override
    public void onItemGiveLikeClickListener(int comment_id, int position) {
        praisePosition = position;
        if (UserInfoUtils.getUserInfo() != null) {
            presenter.getCommentlike(bean.getId(), comment_id);
        } else {
            LoginUtils.toLogin(this);
        }
    }

    private int INTENT_USER_HOME_QUESTCODE = 1008;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == INTENT_USER_HOME_QUESTCODE) {
                boolean booleanExtra = data.getBooleanExtra(Constant.IS_COLLECT, false);
                isConcern = booleanExtra;
                keepAuthorLayout.setVisibility(isConcern ? View.GONE : View.VISIBLE);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        presenter.onDestory();
    }
}
